package com.eriloan.easyPage.filter;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.eriloan.easyPage.beans.ListenerBean;
import com.eriloan.easyPage.beans.RouteInfo;
import com.eriloan.easyPage.exception.ControllerException;
import com.eriloan.easyPage.exception.ConversionTypeException;
import com.eriloan.easyPage.exception.ListenerException;
import com.eriloan.easyPage.exception.OperateSpringBeanException;
import com.eriloan.easyPage.exception.UnknownException;
import com.eriloan.easyPage.service.IEasyPageService;
import com.eriloan.easyPage.service.impl.EasyPageServiceImpl;
import com.eriloan.easyPage.util.EasyPageContext;

/**
 * 
 * <p>Copyright: All Rights Reserved</p>
 * <p>Company: 北京荣之联科技股份有限公司 http://www.ronglian.com</p>
 * <p>Description: EasyPage 初始化 拦截器 </p>
 * <p>Author:Eric Shi/史丙利</p>
 */
public class EasyPageStartupFilter implements Filter{

	/**
	 * 项目包的根路径
	 */
	private String rootPkg = null;

	/**
	 * Controller 过滤
	 */
	private String controllerFilters = null;

	/**
	 * 页面后缀名
	 */
	private String pageSuffix = null;

	/**
	 * 项目编码
	 */
	private String charset = null;

	/**
	 * 是否支持 Spring
	 */
	private boolean isSupportSpring = false;

	/**
	 * 框架处理的 service
	 */
	private IEasyPageService easyPageService = null;

	/**
	 * 路由集合
	 */
	private LinkedList<RouteInfo> routeInfos = null;

	/**
	 * 监听类集合
	 */
	private LinkedList<ListenerBean> listenerBeans = null;

	/**
	 * 是否支持模板
	 */
	private boolean isTemplateView = false;

	/**
	 * 模板类型
	 */
	private String templateType;

	/**
	 * 模板配置文件路径
	 */
	private String templateConfigPath;

	/**
	 * Eclipse页面内容目录
	 */
	private String eclipseContentDirectory;

	/**
	 * 
	 * <br/>Description:构造方法
	 * <p>Author:Eric Shi/史丙利</p>
	 */
	public EasyPageStartupFilter(){
	}

	public void destroy(){
	}

	/**
	 * 
	 * <p>Description:Dispatcher请求方法</p>
	 * <p>Author:Eric Shi/史丙利</p>
	 * 
	 * @Title: doFilter
	 * @param request
	 * @param response
	 * @param chain
	 * @throws IOException
	 * @throws ServletException
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException{
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		// 编码处理
		req.setCharacterEncoding(this.charset);
		res.setCharacterEncoding(this.charset);
		res.setContentType("text/html; charset=" + this.charset);

		// 缓存处理
		res.setHeader("Pragma","No-cache");
		res.setHeader("Cache-Control","no-cache");
		res.setDateHeader("Expires", - 1);

		EasyPageContext.threadLocalRequest.set(req);

		EasyPageContext.threadLocalResponse.set(res);

		EasyPageContext.threadLocalPageSuffix.set(pageSuffix);

		EasyPageContext.threadLocalCharset.set(charset);

		EasyPageContext.threadLocalIsTemplateView.set(isTemplateView);

		EasyPageContext.threadLocalTemplateConfigPath.set(templateConfigPath);

		EasyPageContext.threadLocalTemplateType.set(templateType);

		EasyPageContext.threadLocalEclipseContentDirectory.set(eclipseContentDirectory);

		String method = req.getMethod().toLowerCase();

		String pathInfo = req.getServletPath();

		Map<String,Object> map = easyPageService.isRouteInfos(routeInfos,pathInfo,method);

		if(Boolean.parseBoolean(map.get("isRouteInfos").toString())){
			RouteInfo routeInfo = (RouteInfo) map.get("routeInfo");

			try{
				easyPageService.methodInvoke(routeInfo,listenerBeans,isSupportSpring);
			}catch(ConversionTypeException e){
				e.printStackTrace();
			}catch(ListenerException e){
				e.printStackTrace();
			}catch(OperateSpringBeanException e){
				e.printStackTrace();
			}catch(ControllerException e){
				e.printStackTrace();
			}catch(UnknownException e){
				e.printStackTrace();
			}
		}else{
			chain.doFilter(req,res);
		}
	}

	/**
	 * 
	 * <p>Description:初始化参数处理</p>
	 * <p>Author:Eric Shi/史丙利</p>
	 * 
	 * @Title: init
	 * @param config
	 * @throws ServletException
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig config) throws ServletException{

		System.out.println("============================");
		System.out.println("= Loading EasyPage......   =");
		System.out.println("=  http://www.eriloan.net  =");
		System.out.println("============================");

		String rpkg = config.getInitParameter("rootPkg");

		String filterVal = config.getInitParameter("controllerFilters");
		String suffixVal = config.getInitParameter("pageSuffix");
		String charsetVal = config.getInitParameter("charset");
		String supportSpring = config.getInitParameter("isSupportSpring");
		String tempView = config.getInitParameter("isTemplateView");
		String tempType = config.getInitParameter("templateType");
		String tempConfPath = config.getInitParameter("templateConfigPath");
		String eContentDirectory = config.getInitParameter("eclipseContentDirectory");

		if(null == rpkg || "".equals(rpkg)){
			System.out.println("无法找到项目的根包");
		}else{
			this.rootPkg = rpkg;
		}

		if(null == filterVal || "".equals(filterVal)){
			this.controllerFilters = "*";
		}else{
			this.controllerFilters = filterVal;
		}

		if(null == suffixVal || "".equals(suffixVal)){
			this.pageSuffix = ".jsp";
		}else{
			this.pageSuffix = suffixVal;
		}

		if(null == charsetVal || "".equals(charsetVal)){
			this.charset = "UTF-8";
		}else{
			this.charset = charsetVal;
		}

		if(null == supportSpring || "".equals(supportSpring)){
			this.isSupportSpring = false;
		}else{
			if("true".equalsIgnoreCase(supportSpring)){
				this.isSupportSpring = true;
			}else{
				this.isSupportSpring = false;
			}
		}

		if(null == tempView || "".equals(tempView)){
			this.isTemplateView = false;
		}else{
			if("true".equalsIgnoreCase(tempView)){
				this.isTemplateView = true;
			}else{
				this.isTemplateView = false;
			}
		}

		if(null == tempType || "".equals(tempType)){
			this.templateType = "velocity";
		}else{
			this.templateType = tempType;
		}

		if(null == tempConfPath || "".equals(tempConfPath)){
			this.templateConfigPath = "WEB-INF/velocity.properties";
		}else{
			this.templateConfigPath = tempConfPath;
		}

		if(null == eContentDirectory || "".equals(eContentDirectory)){
			this.eclipseContentDirectory = "WebContent";
		}else{
			this.eclipseContentDirectory = eContentDirectory;
		}

		easyPageService = new EasyPageServiceImpl();

		routeInfos = easyPageService.getRouteInfos(rootPkg,controllerFilters);

		listenerBeans = easyPageService.getlistenerBeans(rootPkg);
	}
}
